package cn.mastor.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class GetToken {
    // 发送get请求
    public static String sendGet(String url, String param) {
        String result = "";
        String urlName = url + "?" + param;        
        try {
            URL realUrl = new URL(urlName);
            System.out.println("这是啥"+realUrl);
            URLConnection conn = realUrl.openConnection();
            conn.connect();
            Map<String, List<String>> map = conn.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key + ":" + map.get(key));
            }

            try (
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))
                ){
                    String line;
                    while ((line = in.readLine()) != null) {
                        result += "\n" + line;
                  }
            }
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
//        System.out.println("这是啥"+result);
        return result;
    }
    // 从指定url中获取access_token, 注意accessToken_request_url参数测试环境和正式环境的区别
    public static String getToken(String appid, String serverSecret, String accessToken_request_url){
        // 从请求access_token的url中获取返回的数据
        String retStr_getTokenUrl = GetToken.sendGet(accessToken_request_url, "appid="+appid+"&secret="+serverSecret);
        // 解析并获取access_token
        String access_token = JSONObject.parseObject(retStr_getTokenUrl).getJSONObject("data").getString("access_token");
        return access_token;
    }
}